/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.flux.utils;

import com.arisgo.cloud.core.Constant;
import com.arisgo.cloud.core.redis.UserInfo;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Arisgo
 * @since 2024/7/17
 */
public class RequestUtil {

    public static Mono<String> getUsername(ServerWebExchange exchange) {
        return getUser(exchange).map(UserInfo::getUsername);
    }

    public static Mono<String> getTenantName(ServerWebExchange exchange) {
        return getUser(exchange).map(UserInfo::getTenantName);
    }

    public static Mono<UserInfo> getUser(ServerWebExchange exchange) {
        return exchange.getSession()
                .map(session -> session.getAttribute(Constant.LOGIN_USER))
                .cast(UserInfo.class)
                .switchIfEmpty(Mono.error(new IllegalStateException("账号未登陆")));
    }

    public static Mono<UserInfo> getUserInfo(ServerWebExchange exchange) {
        return exchange.getSession()
                .map(session -> session.getAttribute(Constant.LOGIN_USER))
                .cast(UserInfo.class);
    }

    public static Mono<Long> getUserId(ServerWebExchange exchange) {
        return Mono.justOrEmpty(exchange.getRequest().getQueryParams().getFirst(UserInfo.USER_ID))
                .map(Long::valueOf);
    }

    public static Mono<Long> getTenantId(ServerWebExchange exchange) {
        return Mono.justOrEmpty(exchange.getRequest().getQueryParams().getFirst(UserInfo.TENANT_ID))
                .map(Long::valueOf);
    }

    public static Mono<Long> getStaffId(ServerWebExchange exchange) {
        return Mono.justOrEmpty(exchange.getRequest().getQueryParams().getFirst(UserInfo.STAFF_ID))
                .map(Long::valueOf);
    }

    public static Mono<String> getRequestPath(ServerWebExchange exchange) {
        return Mono.just(exchange.getRequest().getPath().value());
    }
}
